﻿
namespace Leetcode.N0227;
public class Solution
{
    public int Calculate(string s)
    {
        int index = 0;
        return this.Calculate(s, ref index);
    }

    private int Calculate(string s, ref int index)
    {
        char op = '+';
        var stack = new Stack<int>();

        for (; index < s.Length; index++)
        {
            switch (s[index])
            {
                case '+':
                    op = '+';
                    break;
                case '-':
                    op = '-';
                    break;
                case '/':
                    op = '/';
                    break;
                case '*':
                    op = '*';
                    break;
                case ' ':
                    break;
                default:
                    var val = this.ReadVal(s, ref index);

                    switch (op)
                    {
                        case '+':
                            this.PushValue(stack, val);
                            break;
                        case '-':
                            this.PushValue(stack, -val);
                            break;
                        case '*':
                            this.PushValue(stack, val, true);
                            break;
                        case '/':
                            this.PushValue(stack, val, false);
                            break;
                    }
                    break;
            }
        }
        return this.GetResult(stack);
    }

    private int ReadVal(string s, ref int index)
    {
        var val = s[index] - '0';
        while (index < s.Length - 1 && s[index + 1] >= '0' && s[index + 1] <= '9')
        {
            index++;
            val = val * 10 + s[index] - '0';
        }
        return val;
    }

    private void PushValue(Stack<int> stack, int value)
    {
        if (stack.Count >= 2)
        {
            stack.Push(this.GetResult(stack));
        }
        stack.Push(value);
    }

    private void PushValue(Stack<int> stack, int value, bool isMultiply)
    {
        int val = stack.Pop();
        stack.Push(isMultiply ? val * value : val / value);
    }

    private int GetResult(Stack<int> stack)
    {
        var sum = 0;
        while (stack.Count > 0)
        {
            sum += stack.Pop();
        }
        return sum;

    }

}